#include "ModulesModel.h"
#include "QTreeModelItem.h"
#include "../XgModulesExplorer/XgW32Module.h"
#include "../XgModulesExplorer/XgW32ProcessModule.h"
#include <QString>

//////////////////////////////////////////////////////////////////////////

class ModuleItem : public QTreeModelItem
{
public:
	ModuleItem(XgW32Module module, QTreeModelItem* pItem, QObject *parent)
		: _module(module), QTreeModelItem(pItem, parent)
	{
		
	}

	~ModuleItem()
	{

	}

	virtual QVariant data(size_t column, int role = Qt::DisplayRole) 
	{
		if( role == Qt::DisplayRole )
		{
			return QString(_module.name().c_str());
		}
		return QVariant();
	}

private:
	XgW32Module _module;
};

class ProcessModuleItem : public QTreeModelItem
{

};

//////////////////////////////////////////////////////////////////////////

ModulesModel::ModulesModel(XgModulesCollector* collector, QObject *parent)
	: QAbstractItemModel(parent)
{
	_collector = collector;
}

void ModulesModel::populate(XgModulesCollector* collector)
{
	_root = new QTreeModelItem(NULL, this);
	
	for( XgModulesCollector::Iterator iter = collector->begin(); iter != collector->end(); iter++ )
	{
		XgW32Module module = iter->second;
		_root->addItem( new ModuleItem(module, _root, _root) );
	}
}

ModulesModel::~ModulesModel()
{

}

QModelIndex ModulesModel::index ( int row, int column, const QModelIndex & parent /*= QModelIndex()*/ ) const
{
	QTreeModelItem* pItem;
	if( !parent.isValid() )
	{
		pItem = (QTreeModelItem*)parent.internalPointer();
	}
	else
	{
		pItem = _root;
	}
	return createIndex( row, column, pItem->item(row) );
}

QModelIndex ModulesModel::parent ( const QModelIndex & index ) const
{
	QTreeModelItem* item = (QTreeModelItem*)index.internalPointer();
	QTreeModelItem* pItem = item->parentItem();
	
	return createIndex(pItem->index(), 0, (void*)pItem);
}

int ModulesModel::rowCount ( const QModelIndex & parent /*= QModelIndex()*/ ) const
{
	QTreeModelItem* item = (QTreeModelItem*)parent.internalPointer();
	return item->itemsCount();
}

int ModulesModel::columnCount ( const QModelIndex & parent /*= QModelIndex()*/ ) const
{
	return 1;
}

QVariant ModulesModel::data ( const QModelIndex & index, int role /*= Qt::DisplayRole*/ ) const
{
	QTreeModelItem* item = (QTreeModelItem*)index.internalPointer();
	QVariant ret = item->data(index.column(), role);
	return ret;
}